 
import {
  Application,
  FrontendOrBackendSession,
  HandlerCallback,
  IHandlerFilter,
  RESERVED,
  RouteRecord
} from 'pinus';
import net_result from '../consts/net_result';

 
export class ErrorHandlerFilter implements IHandlerFilter {
  public app: Application;
  constructor (app: Application) {
    this.app = app;
    this.app.set(RESERVED.ERROR_HANDLER, this.handler.bind(this));
    this.app.set(RESERVED.GLOBAL_ERROR_HANDLER, this.handler.bind(this));
  }

  public before (routeRecord: RouteRecord, msg: any, session: FrontendOrBackendSession, next: HandlerCallback){
  
    next(null);
  }

  public after (err: Error, routeRecord: RouteRecord, msg: any, session: FrontendOrBackendSession, resp: any, next: HandlerCallback){
    
    return next(null);
  }

  private handler (err: any, msg, resp, session, next){
      if(!resp){
        console.error(err);
         next(null,net_result.error());
      }
       next(null, resp);
  }
}

export default function (app: Application) {
  return new ErrorHandlerFilter(app);
}